import 'dart:math';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:my_edge_detection/edge_detection.dart';

import 'edge_painter.dart';

class EdgeDetectionDraw extends StatefulWidget {
  EdgeDetectionDraw(
      {@required this.renderedImageSize,
      @required this.originalImageSize,
      @required this.edgeDetectionResult});

  final Size renderedImageSize;
  final Size originalImageSize;
  final EdgeDetectionResult edgeDetectionResult;

  @override
  _EdgeDetectionDrawState createState() => _EdgeDetectionDrawState();
}

class _EdgeDetectionDrawState extends State<EdgeDetectionDraw> {
  double edgeDraggerSize;

  List<Offset> points;

  double renderedImageWidth;
  double renderedImageHeight;
  double top;
  double left;

  Offset currentDragPosition;

  @override
  void didChangeDependencies() {
    double shortestSide = min(
        MediaQuery.of(context).size.width, MediaQuery.of(context).size.height);
    edgeDraggerSize = shortestSide / 12;
    super.didChangeDependencies();
  }

  @override
  void initState() {
    _calculateDimensionValues();

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    points = [
      Offset(left + widget.edgeDetectionResult.topLeft.dx * renderedImageWidth,
          top + widget.edgeDetectionResult.topLeft.dy * renderedImageHeight),
      Offset(left + widget.edgeDetectionResult.topRight.dx * renderedImageWidth,
          top + widget.edgeDetectionResult.topRight.dy * renderedImageHeight),
      Offset(
          left + widget.edgeDetectionResult.bottomRight.dx * renderedImageWidth,
          top +
              (widget.edgeDetectionResult.bottomRight.dy *
                  renderedImageHeight)),
      Offset(
          left + widget.edgeDetectionResult.bottomLeft.dx * renderedImageWidth,
          top + widget.edgeDetectionResult.bottomLeft.dy * renderedImageHeight),
      Offset(left + widget.edgeDetectionResult.topLeft.dx * renderedImageWidth,
          top + widget.edgeDetectionResult.topLeft.dy * renderedImageHeight),
    ];

    return CustomPaint(
        painter: EdgePainter(
            points: points,
            color: Theme.of(context).accentColor.withOpacity(0.5)));
  }

  void _calculateDimensionValues() {
    top = 0.0;
    left = 0.0;

    double widthFactor =
        widget.renderedImageSize.width / widget.originalImageSize.width;
    double heightFactor =
        widget.renderedImageSize.height / widget.originalImageSize.height;
    double sizeFactor = min(widthFactor, heightFactor);

    renderedImageHeight = widget.originalImageSize.height * sizeFactor;
    top = ((widget.renderedImageSize.height - renderedImageHeight) / 2);

    renderedImageWidth = widget.originalImageSize.width * sizeFactor;
    left = ((widget.renderedImageSize.width - renderedImageWidth) / 2);
  }
}
